<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>milkcode - 分享你的资源</title>
    <link rel="stylesheet" href="/styles.css">
    <script th:if="${session.user == null}" src="/js/ad.js"></script>
    <style>
        .timeline {
            margin-top: 90px;
            padding-top: 2rem;
        }

        @media (max-width: 600px) {
            .timeline {
                margin-top: 180px;
            }
        }

        .user-info {
            display: flex;
            align-items: center;
            gap: 15px;
            background: #f8f9fa;
            padding: 6px 15px;
            border-radius: 8px;
            border: 1px solid #e9ecef;
        }

        .user-name {
            color: #333;
            font-weight: 500;
            font-size: 14px;
            padding: 0 10px;
            border-right: 1px solid #dee2e6;
        }

        .user-info .nav-link {
            color: #495057;
            text-decoration: none;
            font-size: 13px;
            padding: 4px 10px;
            border-radius: 4px;
            transition: all 0.2s ease;
        }

        .user-info .nav-link:hover {
            color: var(--primary-color);
            background: #e9ecef;
        }

        /* 调整导航栏按钮的样式 */
        .nav-buttons {
            display: flex;
            align-items: center;
            gap: 12px;
        }

        .login-btn {
            background: var(--primary-color);
            color: white;
            padding: 6px 16px;
            border-radius: 6px;
            text-decoration: none;
            font-size: 13px;
            transition: all 0.2s ease;
        }

        .login-btn:hover {
            background: var(--secondary-color);
        }

        .user-info .nav-link:active {
            transform: translateY(0);
        }
    </style>
</head>
<body>
    <header>
        <div class="header-content">
            <h1>milkcode</h1>
            <nav class="header-nav">
                <div class="search-container">
                    <input type="text" class="search-input" placeholder="搜索资源..." id="searchInput" th:value="${keyword}">
                    <svg class="search-icon" viewBox="0 0 24 24" th:if="${keyword != null}" style="cursor: pointer;" onclick="clearSearch()">
                        <path fill="currentColor" d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"/>
                    </svg>
                    <svg class="search-icon" viewBox="0 0 24 24" th:unless="${keyword != null}">
                        <path fill="currentColor" d="M15.5 14h-.79l-.28-.27C15.41 12.59 16 11.11 16 9.5 16 5.91 13.09 3 9.5 3S3 5.91 3 9.5 5.91 16 9.5 16c1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99L20.49 19l-4.99-5zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z"/>
                    </svg>
                </div>
                <div class="nav-buttons">
                    <a href="login" class="login-btn" th:if="${session.user == null}">登录去广告</a>
                    <div class="user-info" th:if="${session.user != null}">
                        <a href="/my-collections" class="nav-link">我的收藏</a>
                        <span class="user-name" th:text="${session.user.userName}">用户名</span>
                        <a href="javascript:void(0)" class="nav-link" onclick="handleLogout()">退出</a>
                    </div>
                    <a href="contact" class="contact-btn">
                        <span>联系我们</span>
                        <svg class="contact-icon" viewBox="0 0 24 24" width="18" height="18">
                            <path fill="currentColor" d="M20 4H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2zm0 4l-8 5-8-5V6l8 5 8-5v2z"/>
                        </svg>
                    </a>
                </div>
            </nav>
        </div>
    </header>

    <main class="timeline">
        <!-- 资源列表 -->
        <div class="timeline-items">
            <div class="timeline-item" th:each="resource : ${resources}">
                <div class="timeline-cover">
                    <img th:src="${resource.coverUrl != null ? resource.coverUrl : 'https://picsum.photos/800/400'}" 
                         th:alt="${resource.title}">
                </div>
                <div class="timeline-content">
                    <div class="timeline-date" th:text="${#dates.format(resource.createTime, 'yyyy年M月')}">2024年3月</div>
                    <h2 th:text="${resource.title}">资源标题</h2>
                    <p class="resource-description" 
                       th:text="${#strings.abbreviate(resource.content, 100)}">资源描述</p>
                    <a th:href="@{'/resource/id/' + ${resource.id}}" class="resource-link">
                        <span>查看详情</span>
                    </a>
                </div>
            </div>
        </div>

        <!-- 分页控件 -->
        <div class="pagination" th:if="${totalPages > 1}">
            <button class="pagination-prev" th:disabled="${currentPage == 1}" onclick="changePage(currentPage - 1)">
                <span>上一页</span>
            </button>
            <div class="pagination-numbers">
                <!-- 第一页 -->
                <button class="pagination-number" 
                        th:classappend="${currentPage == 1 ? 'active' : ''}"
                        onclick="changePage(1)">1</button>
                
                <!-- 左侧省略号 -->
                <span class="pagination-ellipsis" 
                      th:if="${currentPage > 3}">...</span>
                
                <!-- 中间页码 -->
                <button th:each="pageNum : ${#numbers.sequence(
                    T(Math).max(2, currentPage - 1),
                    T(Math).min(totalPages - 1, currentPage + 1)
                )}"
                        class="pagination-number"
                        th:classappend="${pageNum == currentPage ? 'active' : ''}"
                        th:onclick="'changePage(' + ${pageNum} + ')'"
                        th:text="${pageNum}">2</button>
                
                <!-- 右侧省略号 -->
                <span class="pagination-ellipsis" 
                      th:if="${currentPage < totalPages - 2}">...</span>
                
                <!-- 最后一页 -->
                <button th:if="${totalPages > 1}"
                        class="pagination-number"
                        th:classappend="${currentPage == totalPages ? 'active' : ''}"
                        th:onclick="'changePage(' + ${totalPages} + ')'"
                        th:text="${totalPages}">10</button>
            </div>
            <button class="pagination-next" th:disabled="${currentPage == totalPages}" onclick="changePage(currentPage + 1)">
                <span>下一页</span>
            </button>
        </div>
    </main>

    <footer>
        <p>© 2024 milkcode. All rights reserved.</p>
    </footer>

    <!-- 添加分页相关的 JavaScript -->
    <script th:inline="javascript">
        // 获取当前页码和总页数
        let currentPage = /*[[${currentPage}]]*/ 1;
        const totalPages = /*[[${totalPages}]]*/ 1;
        
        // 清除搜索
        async function clearSearch() {
            const searchInput = document.getElementById('searchInput');
            searchInput.value = '';
            
            // 更新 URL，移除搜索关键词
            const url = new URL(window.location);
            url.searchParams.delete('keyword');
            url.searchParams.set('page', '1');
            window.history.pushState({}, '', url);
            
            // 重新加载数据
            const timelineItems = document.querySelector('.timeline-items');
            timelineItems.classList.add('page-transition');
            
            try {
                const response = await fetch('/api/resources?pageNum=1&pageSize=8');
                if (!response.ok) {
                    throw new Error('网络请求失败');
                }
                const data = await response.json();
                
                if (!data || !data.list) {
                    throw new Error('返回数据格式错误');
                }
                
                // 更新内容
                updateContent(data);
                
                // 更新分页按钮状态
                updatePagination(1, data.pages);
                
                // 更新当前页码
                currentPage = 1;
                
                // 滚动到页面顶部
                window.scrollTo({
                    top: 0,
                    behavior: 'smooth'
                });
            } catch (error) {
                console.error('加载数据失败:', error);
                alert('加载数据失败，请稍后重试');
            } finally {
                timelineItems.classList.remove('page-transition');
            }
        }

        // 页面加载时检查是否需要清除搜索
        window.addEventListener('load', function() {
            const url = new URL(window.location);
            if (url.searchParams.has('keyword')) {
                // 如果有搜索关键词，显示清除按钮
                const searchIcon = document.querySelector('.search-icon');
                if (searchIcon) {
                    searchIcon.style.cursor = 'pointer';
                    searchIcon.onclick = clearSearch;
                }
            }
        });

        // 添加搜索功能
        document.getElementById('searchInput').addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                const keyword = this.value.trim();
                if (keyword) {
                    // 重置页码并搜索
                    currentPage = 1;
                    searchResources(keyword);
                } else {
                    // 如果搜索框为空，跳转到首页
                    window.location.href = '/';
                }
            }
        });

        // 搜索资源
        async function searchResources(keyword) {
            const timelineItems = document.querySelector('.timeline-items');
            timelineItems.classList.add('page-transition');
            
            try {
                const response = await fetch(`/api/resources?pageNum=1&pageSize=8&keyword=${encodeURIComponent(keyword)}`);
                if (!response.ok) {
                    throw new Error('网络请求失败');
                }
                const data = await response.json();
                
                if (!data || !data.list) {
                    throw new Error('返回数据格式错误');
                }
                
                // 更新 URL，添加搜索关键词
                const url = new URL(window.location);
                url.searchParams.set('keyword', keyword);
                url.searchParams.set('page', '1');
                window.history.pushState({}, '', url);
                
                // 更新内容
                updateContent(data);
                
                // 更新分页按钮状态
                updatePagination(1, data.pages);
                
                // 更新当前页码
                currentPage = 1;
                
                // 滚动到页面顶部
                window.scrollTo({
                    top: 0,
                    behavior: 'smooth'
                });
            } catch (error) {
                console.error('搜索失败:', error);
                alert('搜索失败，请稍后重试');
            } finally {
                timelineItems.classList.remove('page-transition');
            }
        }

        // 页面切换函数
        async function changePage(pageNum) {
            if (pageNum < 1 || pageNum > totalPages) {
                return;
            }

            const timelineItems = document.querySelector('.timeline-items');
            timelineItems.classList.add('page-transition');
            
            try {
                // 获取当前搜索关键词
                const keyword = document.getElementById('searchInput').value.trim();
                const url = new URL(window.location);
                
                // 发送 AJAX 请求获取新页面数据
                const response = await fetch(`/api/resources?pageNum=${pageNum}&pageSize=8${keyword ? '&keyword=' + encodeURIComponent(keyword) : ''}`);
                if (!response.ok) {
                    throw new Error('网络请求失败');
                }
                const data = await response.json();
                
                if (!data || !data.list) {
                    throw new Error('返回数据格式错误');
                }
                
                // 更新 URL，不刷新页面
                url.searchParams.set('page', pageNum);
                window.history.pushState({}, '', url);
                
                // 更新内容
                updateContent(data);
                
                // 更新分页按钮状态
                updatePagination(pageNum, data.pages);
                
                // 更新当前页码
                currentPage = pageNum;
                
                // 滚动到页面顶部
                window.scrollTo({
                    top: 0,
                    behavior: 'smooth'
                });
            } catch (error) {
                console.error('加载数据失败:', error);
                alert('加载数据失败，请稍后重试');
            } finally {
                timelineItems.classList.remove('page-transition');
            }
        }

        // 更新内容区域
        function updateContent(data) {
            const timelineItems = document.querySelector('.timeline-items');
            if (!data.list || data.list.length === 0) {
                timelineItems.innerHTML = '<div class="no-data">暂无数据</div>';
                return;
            }
            
            timelineItems.innerHTML = data.list.map(resource => `
                <div class="timeline-item">
                    <div class="timeline-cover">
                        <img src="${resource.coverUrl || 'https://picsum.photos/800/400'}" 
                             alt="${resource.title}"
                             onerror="this.src='https://picsum.photos/800/400'">
                    </div>
                    <div class="timeline-content">
                        <div class="timeline-date">${formatDate(resource.createTime)}</div>
                        <h2>${resource.title || '无标题'}</h2>
                        <p class="resource-description">${truncateText(resource.content || '', 100)}</p>
                        <a href="/resource/id/${resource.id}" class="resource-link">
                            <span>查看详情</span>
                        </a>
                    </div>
                </div>
            `).join('');
        }

        // 更新分页按钮
        function updatePagination(currentPage, totalPages) {
            const paginationContainer = document.querySelector('.pagination');
            if (!paginationContainer) return;
            
            const paginationNumbers = document.querySelector('.pagination-numbers');
            const prevButton = document.querySelector('.pagination-prev');
            const nextButton = document.querySelector('.pagination-next');

            if (!paginationNumbers || !prevButton || !nextButton) return;

            // 更新上一页/下一页按钮状态和事件处理
            prevButton.disabled = currentPage === 1;
            nextButton.disabled = currentPage === totalPages;
            
            // 移除旧的事件监听器
            prevButton.onclick = null;
            nextButton.onclick = null;
            
            // 添加新的事件监听器
            prevButton.onclick = () => changePage(currentPage - 1);
            nextButton.onclick = () => changePage(currentPage + 1);

            // 生成页码按钮
            let paginationHtml = `
                <button class="pagination-number ${currentPage === 1 ? 'active' : ''}" 
                        onclick="changePage(1)">1</button>
            `;

            if (currentPage > 3) {
                paginationHtml += '<span class="pagination-ellipsis">...</span>';
            }

            for (let i = Math.max(2, currentPage - 1); i <= Math.min(totalPages - 1, currentPage + 1); i++) {
                paginationHtml += `
                    <button class="pagination-number ${i === currentPage ? 'active' : ''}" 
                            onclick="changePage(${i})">${i}</button>
                `;
            }

            if (currentPage < totalPages - 2) {
                paginationHtml += '<span class="pagination-ellipsis">...</span>';
            }

            if (totalPages > 1) {
                paginationHtml += `
                    <button class="pagination-number ${currentPage === totalPages ? 'active' : ''}" 
                            onclick="changePage(${totalPages})">${totalPages}</button>
                `;
            }

            paginationNumbers.innerHTML = paginationHtml;
        }

        // 格式化日期
        function formatDate(dateStr) {
            if (!dateStr) return '';
            const date = new Date(dateStr);
            if (isNaN(date.getTime())) return '';
            return `${date.getFullYear()}年${date.getMonth() + 1}月`;
        }

        // 截断文本
        function truncateText(text, maxLength) {
            if (!text) return '';
            return text.length > maxLength ? text.substring(0, maxLength) + '...' : text;
        }

        // 处理退出登录
        async function handleLogout() {
            try {
                const response = await fetch('/api/logout');
                const result = await response.json();
                
                if (result.success) {
                    window.location.reload();
                } else {
                    alert(result.message || '退出失败，请稍后重试');
                }
            } catch (error) {
                console.error('退出请求失败:', error);
                alert('退出请求失败，请稍后重试');
            }
        }

        // 添加错误处理样式
        const style = document.createElement('style');
        style.textContent = `
            .no-data {
                text-align: center;
                padding: 2rem;
                color: #64748b;
                font-size: 1.1rem;
            }
            .page-transition {
                opacity: 0.6;
                transition: opacity 0.3s ease;
            }
            .user-info {
                display: flex;
                align-items: center;
                gap: 15px;
            }

            .user-name {
                color: var(--primary-color);
                font-weight: 500;
            }

            .user-info .nav-link {
                color: #666;
                text-decoration: none;
                transition: color 0.3s;
            }

            .user-info .nav-link:hover {
                color: var(--primary-color);
            }
        `;
        document.head.appendChild(style);
    </script>
</body>
</html>
